import { Modal, Form, Input, Button, Tag, Popconfirm } from 'antd';
import { CloseCircleFilled } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import moment from 'moment';
import { pickTaskQuickQueryList, pickTaskQuickQuerySave, pickTaskQuickQueryDelete } from './service';

// 使用说明： 
    // module: 模块， type: 类型， resetKey: 重置， resetClick: 重置按钮点击事件，主要是更新了选中状态
    // query: 查询条件， handleClick: 点击查询事件， updateQuickQueryList: 更新快捷查询列表

    // 1拿货任务待拿货列表 2拿货任务待分配列表 3拿货任务待指派列表 
    // 4代拿任务待拿货列表 5代拿任务待指派列表 6代拿任务拿货异常 7代拿任务已拿货列表 
    // 8订单处理全部 9订单处理待审核 10订单处理待付款 11订单处理异常订单 12订单处理待发货 13订单处理已取件 14订单处理已发货15订单处理作废订单 16订单处理历史订单 
    // 17打单发货待发货 18打单发货已发货 
    // 19打单发货新版待审核 20打单发货新版待支付 21打单发货新版异常订单 22打单发货新版待发货 23打单发货新版已发货 24打单发货新版作废订单 25打单发货新版全部订单 26打单发货新版售后 
    // 27仓库订单全部 28仓库订单待拿货 29仓库订单待包装 30仓库订单待发货 31仓库订单已取件 32仓库订单已发货 33仓库订单异常 34仓库订单已作废 35仓库订单历史数据 
    // 36三方出库单"

export default ({module, type, resetKey, resetClick, query, delConfirm = false, maxLength = 8, handleClick, updateQuickQueryList }) => {
    console.log(query,'commonQuickQuery-query');
    
    let enumUsePage = {
        '1': {
            '0': 1,
            '1': 3,
            '3': 2,
            '2': 4,
        },
        // 代拿货
        '2': {
            '0': 4,
            '1': 5,
            '50': 6,
            '2': 7,
        },
        '3': {
            '0': 8,
            '1': 9,
            '2': 10,
            '3': 11,
            '4': 12,
            '5': 13,
            '6': 14,
            '7': 15,
            '8': 16,
        },
        '4': {
            '1': 17,
            '2': 18,
        },
        '5': {
            '0': 27,
            '1': 28,
            '2': 29,
            '3': 30,
            '4': 31,
            '5': 32,
            '6': 33,
            '7': 34,
            '8': 35,
        },
        '6': {
            '0': 36,
        },
        '7': {
            '1': 19,
            '2': 20,
            '3': 21,
            '4': 22,
            '6': 23,
            '7': 24,
            '0': 25,
        },
    }
    //快捷查询列表
	const [quickQueryList, setQuickQueryList] = useState([]);
	const [tagFocusIndex, setTagFocusIndex] = useState('');
    const [tagSelectIndex, setTagSelectIndex] = useState('');

    //另存为快捷查询弹窗
	const [saveQuickQueryVisible, setSaveQuickQueryVisible] = useState(false);
    
    useEffect(() => {
        quickQueryListFunc();
        setTagSelectIndex('')
    },[module, type])

    useEffect(() => {
        setTagSelectIndex('');
    },[resetClick])

    // 另存为快捷查询新增弹窗
    const [form] = Form.useForm();
    const layout = {
        labelCol: {
            span: 8,
        },
        wrapperCol: {
            span: 12,
        },
    };

    //点击另存问快捷查询
    const saveQuickQuery = () => {
        form.resetFields();
		setSaveQuickQueryVisible(true);
	}

    // 快捷查询新增弹窗确定
    const saveQuickQueryOk = () => {
        form.validateFields().then(values => {
            if(values) {
                if (maxLength && quickQueryList.length >= maxLength) {
                    Modal.info({
                        content: `快捷查询最多保存${maxLength}条`
                    })
                    return;
                }
                quickQuerySaveFunc(values);
            }
        })
    }
    // 快捷查询新增弹窗取消
    const saveQuickQueryCancel = () => {
        setSaveQuickQueryVisible(false);
    }

    // 快捷查询
	const quickQueryListFunc = async () => {
        console.log('pickTaskQuickQueryList');
		const res = await pickTaskQuickQueryList({ usePage: enumUsePage[module][type] });
		if (res.success) {
			setQuickQueryList(res.data);
            console.log(res.data);
            if(updateQuickQueryList) {
                updateQuickQueryList(res.data);
            }
		}
	}

	// 快捷新增
	const quickQuerySaveFunc = async (values) => {
        let momentKeys = [];
        if(Object.keys(query).length > 0) {
            Object.keys(query).forEach(item => {
                if(query[item] && typeof query[item] === 'object' && query[item]._isAMomentObject) {
                    momentKeys.push(item);
                    query[item] = moment(query[item]).format('YYYY-MM-DD HH:mm:ss');
                }
                if(Array.isArray(query[item]) && query[item].length > 0){
                    if(query[item][0] && typeof query[item][0] === 'object' && query[item][0]._isAMomentObject) {
                        momentKeys.push(item);
                        query[item].forEach(it => {
                            it = moment(it).format('YYYY-MM-DD HH:mm:ss');
                        })
                        // query[item] = moment(query[item]);
                    }
                }
            })
        }
        let params = {...query};
        if(momentKeys.length > 0) {
            params['momentKeys'] = momentKeys.join(',');
        }else{
            delete params['momentKeys'];
        }
        console.log(params);
        console.log(JSON.stringify(params));
		const res = await pickTaskQuickQuerySave({
            name: values.name,
            usePage: enumUsePage[module][type],
            queryParam: JSON.stringify(params)
        });
		if (res.success) {
			setSaveQuickQueryVisible(false);
			quickQueryListFunc();
		}
	}

	//快捷查询删除
	const quickQueryDelConfirm = async (item, index, e) => {
		e.preventDefault();
		let res = await pickTaskQuickQueryDelete({ id: item.id })
		setSaveQuickQueryVisible(false);
		if (res.success) {
			quickQueryListFunc();
            setTagSelectIndex('');
		}
	}

    //点击快捷查询元素
    const handleClickQuickQuery = (item, index) => {
        setTagSelectIndex(index);
		let { queryParam } = item;
		if (queryParam) {
			queryParam = JSON.parse(queryParam);
		}
        console.log(queryParam);
        if('momentKeys' in queryParam && queryParam.momentKeys) {
            let momentKeys = queryParam.momentKeys.split(',');
            momentKeys.forEach(it => {
                console.log(it);
                if(Array.isArray(queryParam[it]) && queryParam[it].length > 0){
                    queryParam[it][0] = moment(queryParam[it][0]);
                    queryParam[it][1] = moment(queryParam[it][1]);
                }else{
                    queryParam[it] = moment(queryParam[it])
                }
            })
            // delete queryParam.momentKeys;
        }
        console.log(queryParam);
        if(handleClick) {
            handleClick(item, queryParam, index)
        }
	}

    return (<>
        <Form.Item>
            <Button onClick={saveQuickQuery} style={{ marginRight: '6px' }}>另存为快捷查询</Button>
            {quickQueryList && quickQueryList.length > 0 && quickQueryList.map((item, index) => {
                return (
                    <Tag
                        color={tagSelectIndex === index ? "#0071F0" : "#fff"}
                        key={item.id}
                        style={{ cursor: 'pointer', position: 'relative', padding: '1px 15px', color: tagSelectIndex === index ? '#fff' : '#333', fontSize: '14px' }}
                        onMouseEnter={() => setTagFocusIndex(index)}
                        onMouseLeave={() => setTagFocusIndex('')}
                        onClick={(e) => {
                            handleClickQuickQuery(item, index)
                        }}
                    > {item.name}
                        {
                            delConfirm && tagFocusIndex === index &&
                            <Popconfirm
                                placement="topRight"
                                title="是否删除"
                                onConfirm={(e) => quickQueryDelConfirm(item, index, e)}
                                onCancel={(e) => e.preventDefault()}
                                okText="确定"
                                cancelText="取消"
                            >
                                <div onClick={(e) => e.stopPropagation()} style={{ position: 'absolute', top: '0', right: '0', width: '10px', height: '10px', zIndex: '1000' }}>
                                    <CloseCircleFilled onClick={(e) => e.preventDefault()} className='icon-close' style={{ position: 'absolute', top: '-5px', right: '-5px', color: '#ccc', fontSize: '16px', zIndex: '1000' }} />
                                </div>
                            </Popconfirm>
                        }
                        {
                            !delConfirm && tagFocusIndex === index && 
                            (<div onClick={(e) => e.stopPropagation()} style={{ position: 'absolute', top: '0', right: '0', width: '10px', height: '10px', zIndex: '1000' }}>
                            <CloseCircleFilled onClick={(e) => quickQueryDelConfirm(item, index, e)} className='icon-close' style={{ position: 'absolute', top: '-5px', right: '-5px', color: '#ccc', fontSize: '16px', zIndex: '1000' }} />
                        </div>)
                        }
                    </Tag>
                )
            })}
        </Form.Item>
        <Modal title="另存为快捷查询" open={saveQuickQueryVisible} onOk={saveQuickQueryOk} onCancel={saveQuickQueryCancel} maskClosable={false}>
            <Form {...layout} form={form} style={{margin: '40px auto'}}>
                <Form.Item
                    name="name"
                    label="命名"
                    rules={[
                    {
                        required: true,
                        message: '请输入快捷查询名称',
                    },
                ]}>
                    <Input maxLength={10} placeholder='请输入快捷查询名称'/>
                </Form.Item>
                </Form>
        </Modal>
    </>)
}